#include <atmel_start.h>
#include "mx_debug.h"
#include "mx_common.h"
//#include "alicloud_sds.h"
#include "alicloud_ilop.h"
#include "drv_board.h"
#include "main.h"
#include "iaqcore.h"
/*
const emh_alisds_config_t alisds_config =
{
	.product_info = {
		.name			= "microchip-002",
		.module			= "MICROCHIP_LIVING_AIRBOX_MICROCHIP_002",
		.key			= "Dkqt9OjYC0u0DIWGajKP",
		.secret			= "ciubDzkEOKVi0WS2VZzqAGGIgdmW1dsSatitz6Ie",
		.format			= EMH_ARG_ALISDS_FORMAT_JSON,
	},
	.dev_info = {
		.type			= "AIRBOX",
		.category		= "LIVING",
		.manufacture	= "MICROCHIP",
	}
};
*/
void usr_btn_isr(void);
void usr_clicked_handler(void);
void usr_long_pressed_handler(void);


/**
 * Example of using USART_0 to write "Hello World" using the IO abstraction.
 *
 * Since the driver is asynchronous we need to use statically allocated memory for string
 * because driver initiates transfer and then returns before the transmission is completed.
 *
 * Once transfer has been completed the tx_cb function will be called.
 */

static uint8_t example_USART_0[12] = "Hello World!";

static void tx_cb_USART_0(const struct usart_async_descriptor *const io_descr)
{
	/* Transfer completed */
}

volatile char glass_break_flag = 0;

static void rx_cb(const struct usart_async_descriptor *const io_descr){
	static char buf[128];
	static int index = 0;

	char c;
	if( 1== io_read(io_descr,  &c,  1)){
		buf[index++] = c;
		if( c=='\n'  || index>= 127){
			buf[index]=0;
			index=0;
			printf("rcv:%s\n", buf);
			
			if( strstr(buf, "glass break event") ){
				printf("glass break detected\n");
				glass_break_flag = 1;
			}else if( strstr(buf, "low freq") ){
				printf("low freq event detect\n");
				glass_break_flag = 2;
			}else if( strstr(buf, "pressure event")){
				printf("pressure event detect\n");
				glass_break_flag = 4;
			}
			
			switch(glass_break_flag){
				case 0: //normal
				OLED_ShowString(0, 6, "            ");
				break;
				
				case 1: //break
				OLED_ShowString(0, 6, "evt: break  ");
				break;
				
				case 2: //low freq
				OLED_ShowString(0, 6, "evt: low freq");
				break;
				
				case 4: //pressure
				OLED_ShowString(0, 6, "evt: pressure");
				break;
			}
			
		}
	}
	
}

void USART_0_example(void)
{
	struct io_descriptor *io;
	
	usart_async_register_callback(&USART_0, USART_ASYNC_TXC_CB, tx_cb_USART_0);
	usart_async_register_callback(&USART_0, USART_ASYNC_RXC_CB, rx_cb);
	/*usart_async_register_callback(&USART_0, USART_ASYNC_ERROR_CB, err_cb);*/
	usart_async_get_io_descriptor(&USART_0, &io);
	usart_async_enable(&USART_0);

	
}


btn_instance_t usr_btn =
{
	.port                   = GPIO_PORTA,
	.pin					= PIN_PA02,
	.io_irq                 = usr_btn_isr,
	.idle					= IOBUTTON_IDLE_STATE_HIGH,
	.long_pressed_timeout	= 5000,
	.pressed_func           = usr_clicked_handler,
	.long_pressed_func		= usr_long_pressed_handler,
};

void usr_btn_isr(void)
{
	button_irq_handler(&usr_btn);
}

void usr_clicked_handler(void)
{
	app_log("press");
	//alisds_provision();
	
	//awss_set(1);
}

void usr_long_pressed_handler(void)
{
	app_log("Restore default settings");
	
	OLED_ShowString(OLED_DISPLAY_COLUMN_START, OLED_DISPLAY_ROW_4, "Restore default ");

	//alisds_restore();
	reset_set(1);
}

void property_report(void){
	char str[256];
	
	/*
	sprintf(str, "{\"CO2\":%d,\"TVOC\":%d,\"CurrentTemperature\":%.2f}", iaq_val.co2, iaq_val.tvoc, SHT20_get_temp());
	if( kNoErr == ilop_report_property(str, strlen(str) ) ){
		printf("%s\n",str);
	}*/
	sprintf(str, "{\"gbdevt_state\":%d}", glass_break_flag);
	if( kNoErr == ilop_report_property(str, strlen(str) ) ){
		
		
		printf("%s\n",str);
	}
	
}

uint32_t prev_tick = 0;
void user_ilop_loop(void)
{
	button_srv(&usr_btn);
	SHT20_task();
	
	
	if( glass_break_flag ){
		property_report();
		glass_break_flag = 0;
	}
	
	uint32_t t = mx_hal_ms_ticker_read();
	if( t - prev_tick > 5000){
		prev_tick = t;
	//	iaq_read();
	//	iaq_disp();
	//	property_report();
	}
	return;
}


int main(void)
{
	mx_status err = kNoErr;
	
	/* Initializes MCU, drivers and middleware */
	atmel_start_init();
	
	drv_board_init();
	drv_board_test();
/*	
	OLED_ShowString(OLED_DISPLAY_COLUMN_START, OLED_DISPLAY_ROW_1, "Microchip");
	err = alisds_init(&alisds_config, ALI_HANDLE_MAX);
	require_noerr(err, exit);

	rgbled_task_init();
	SHT20_task_init();
	switch_task_init();
	console_task_init();
	*/
	USART_0_example();
	
	SHT20_task_init();

	button_init(&usr_btn);
	
	i2c_m_sync_get_io_descriptor(&I2C_0, &I2C_0_io);
	i2c_m_sync_enable(&I2C_0);
	i2c_m_sync_set_slaveaddr(&I2C_0, 0x5A, I2C_M_SEVEN); //IAQ SLA
	OLED_ShowString(0,0, "Burnon Glass ");
	OLED_ShowString(0,2, "Break Detect");
	
	//USART_0_example();
	
	application_start();
	
	while(1)
	{
		/* Application tick */
		//alisds_runloop();
		//SHT20_task();
		//switch_task();
		//button_srv(&usr_btn);
	}
	
//exit:
	app_log("App exit reason %d", err);
	while(1);
}


